package perso.marcr.lst.api;

import java.io.IOException;

import perso.marcr.lst.model.Scenario;
import perso.marcr.util.ConverterByte;
import perso.marcr.util.Date;
import perso.marcr.util.Unit;

public class InfoThread extends Thread {

	private Scenario scenario = null;
	private BufferFile bufferFile = null;    
	private boolean bloop = true;	

	public InfoThread(BufferFile bufferFile, Scenario scenario) throws IOException
	{
		this.bufferFile = bufferFile;
		this.scenario = scenario;
	}

	private void sleep()
	{		
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void run()
	{
		long startTime = System.currentTimeMillis();
		try
		{
			while(bloop)
			{
				sleep();
				long currentTime = System.currentTimeMillis();
				printInformations(startTime, currentTime);
			}

			long finishTime = System.currentTimeMillis();
			printInformations(startTime, finishTime);
		}
		catch(IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("FINISH");
	}

	private void printInformations(long startTime, long currentTime) throws IOException
	{
		double nbrTotalBytesCopied = bufferFile.getNbrTotalBytesCopied();

		double nbByteCopied = nbrTotalBytesCopied;
		long timeForCopyInSecond = (currentTime - startTime)/1000;

		double dSpeed = 0; 			// In 0s could not manage to calculate speed.

		if(timeForCopyInSecond>0)
		{
			dSpeed = nbByteCopied/timeForCopyInSecond;
		}		

		// fill result object:
		scenario.setDateEnd(Date.getNow());
		scenario.setSizeCopied(ConverterByte.toHumanReadable(nbByteCopied, Unit.OCTET));
		scenario.setElaspedTime(timeForCopyInSecond);
		scenario.setAverageSpeed(dSpeed, Unit.OCTET);
		scenario.getListAverage().add(ConverterByte.convert(dSpeed, Unit.OCTET, Unit.MO));

		System.out.println("-----------------------");
		System.out.println(scenario);
	}


	public boolean isBloop() {
		return bloop;
	}

	public void setBloop(boolean bloop) {
		this.bloop = bloop;
	}
}
